<template>
  <div class="main">
    <!-- 数据查询区：表单 -->
    <el-form ref="queryRef" :model="queryParams" :inline="true">
      <el-form-item label="订单号" prop="no">
        <el-input
          v-model="queryParams.no"
          placeholder="请输入订单号"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房间号" prop="roomNumber">
        <el-input
          v-model="queryParams.roomNumber"
          placeholder="请输入房间号"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="押金状态" prop="refund">
        <el-select
          v-model="queryParams.refund"
          style="width: 200px"
          placeholder="请选择押金状态"
        >
          <el-option
            v-for="item in refundOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentType">
        <el-select
          v-model="queryParams.paymentType"
          style="width: 200px"
          placeholder="请选择支付方式"
        >
          <el-option
            v-for="item in paymentTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入住日期" prop="startDate">
        <el-date-picker
          v-model="queryParams.startDate"
          type="date"
          placeholder="Pick a day"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="contact">
        <el-input
          v-model="queryParams.contact"
          placeholder="请输入联系人"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入电话"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery(queryRef)">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据展示区：表格 -->
    <el-table v-loading="loading" :data="dataList">
      <el-table-column label="ID" align="center" width="80" prop="id" />
      <el-table-column label="订单号" align="center" width="250" prop="no" />
      <el-table-column
        label="房间号"
        align="center"
        width="90"
        prop="roomNumber"
      />
      <el-table-column label="状态" align="center" width="150" prop="refund">
        <template #default="scope">
          <el-tag :type="getTagType(scope.row.refund)">{{
            scope.row.refund
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="总金额"
        align="center"
        width="80"
        prop="roomRate"
      />
      <el-table-column
        label="支付方式"
        align="center"
        width="120"
        prop="paymentType"
      />
      <el-table-column
        label="入住日期"
        align="center"
        prop="startDate"
        width="120"
      />
      <el-table-column
        label="联系人"
        align="center"
        width="120"
        prop="contact"
      />
      <el-table-column label="电话" align="center" width="120" prop="phone" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="View"
            size="small"
            @click="handleView(scope.row)"
            >查看订单</el-button
          >
          <el-button
            v-if="scope.row.status == '已预定'"
            plain
            type="primary"
            icon="Wallet"
            size="small"
            @click="handlePay(scope.row)"
            >支付订单</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 数据展示区：分页加载 -->
    <el-pagination
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      style="margin-top: 20px"
      :page-sizes="[10, 20, 30, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 数据编辑区：新增/修改对话框 默认不显示 -->
    <el-dialog v-model="open" :title="title" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单ID" prop="saleId">
          {{ saleInfo.saleNo }}
        </el-form-item>
        <el-form-item label="总金额"> {{ saleInfo.total }} 元 </el-form-item>
        <el-form-item label="支付方式" prop="payMethod">
          <el-radio-group v-model="form.payMethod">
            <el-radio value="CASH">现金支付</el-radio>
            <el-radio value="WECHAT">微信支付</el-radio>
            <el-radio value="ALIPAY">支付宝支付</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="支付金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入支付金额" />
        </el-form-item>
        <el-form-item v-if="form.payMethod === 'CASH'" label="找零">
          <el-input v-model="changeDue" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(formRef)"
            >确 定</el-button
          >
          <el-button @click="cancel()">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer v-model="drawer" title="订单明细" :with-header="false">
      <el-descriptions :title="saleItems.no" :column="2" border>
        <el-descriptions-item label="总房费">{{
          saleItems.roomRate
        }}</el-descriptions-item>
        <el-descriptions-item label="房间号">{{
          saleItems.roomNumber
        }}</el-descriptions-item>
        <el-descriptions-item label="押金">{{
          saleItems.deposit
        }}</el-descriptions-item>
        <el-descriptions-item label="押金状态">
          <el-tag :type="getTagType(saleItems.refund)">{{
            saleItems.refund
          }}</el-tag></el-descriptions-item
        >
        <!-- <el-descriptions-item label="订单号">{{
          saleInfo.saleNo
        }}</el-descriptions-item> -->
      </el-descriptions>
      <el-divider />
      <el-scrollbar height="400px">
        <el-table :data="saleItems.list" style="width: 100%">
          <el-table-column type="index" width="50" />
          <el-table-column prop="specificDate" label="日期" />
          <el-table-column prop="price" label="价格" />
        </el-table>
      </el-scrollbar>
      <!-- <el-table :data="saleItems" style="width: 100%">
        <el-table-column prop="itemSn" label="编码" />
        <el-table-column prop="productName" label="名称" />
        <el-table-column prop="price" label="单价" />
        <el-table-column prop="quantity" label="数量" />
      </el-table> -->
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
/** ------------------全局导入区-------------------- */
import { ref, reactive, toRef, onMounted, computed } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import type { SaleInfo, PaymentForm } from "@/api/payment";
import { listSaleByPage, addPayment } from "@/api/payment";
import { getSaleById, listSaleItemById } from "@/api/sale";
import { getPayment, getOrderDetails } from "@/api/roompayment";

onMounted(() => {
  getList();
});

/** ------------------数据查询区——表单-------------------- */
const queryRef = ref<FormInstance>();
const query = reactive({
  pageNum: 1,
  pageSize: 10,
  no: undefined,
  roomNumber: undefined,
  paymentType: undefined,
  refund: undefined,
  startDate: undefined,
  contact: undefined,
  phone: undefined
});
const queryParams = toRef(query);
const refundOptions = [
  { value: "已退", label: "已退" },
  { value: "未退", label: "未退" },
  { value: "超时未退", label: "超时未退" }
];
const paymentTypeOptions = [
  { value: "微信支付", label: "微信支付" },
  { value: "支付宝支付", label: "支付宝支付" },
  { value: "现金支付", label: "现金支付" }
];
// 数据查询区--> 查询按钮
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
// 数据查询区--> 重置按钮
const resetQuery = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  getList();
};

/** ------------------数据展示区——表格-------------------- */
const loading = ref<boolean>(false); // table数据加载遮罩
const total = ref<number>(0); // table数据总数
const tableData = reactive([]); // table数据
const dataList = toRef(tableData);
// 数据展示区--> 数据加载
function getList() {
  loading.value = true;
  /** 调用后端分页查询接口 */
  getPayment(queryParams.value).then(response => {
    dataList.value = response.data.records;
    console.log(dataList.value);
    total.value = response.data.total;
    loading.value = false;
  });
}
// 不同状态显示不同标签
function getTagType(value: string) {
  switch (value) {
    case "未退":
      return "primary";
    case "已退":
      return "success";
    case "超时未退":
      return "danger";
  }
}

/** ------------------数据展示区：分页加载-------------------- */
// 分页--> 修改每页数据数
function handleSizeChange(val: number) {
  queryParams.value.pageSize = val;
  getList();
}

//分页--> 修改当前页
function handleCurrentChange(val: number) {
  queryParams.value.pageNum = val;
  getList();
}

/** ------------------数据编辑区——对话框+表单-------------------- */
const formRef = ref<FormInstance>();
const formData = reactive<PaymentForm>({
  saleId: 0,
  payMethod: "CASH",
  amount: 0.0
});
const form = toRef(formData); // 支付表单
const rules = reactive<FormRules<PaymentForm>>({
  // 表单验证规则
  amount: [
    {
      pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
      message: "支付金额不正确",
      trigger: "blur"
    }
  ]
});

//待支付订单信息
const saleInfo = ref<SaleInfo>({
  saleId: 0,
  saleNo: "",
  total: 0.0,
  status: ""
});
const changeDue = computed(() => {
  return form.value.amount - saleInfo.value.total; //自动计算找零
});
const title = ref(""); // 对话框标题
const open = ref(false); //对话框打开

// 数据编辑区-->提交按钮
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      addPayment(form.value).then(response => {
        ElMessage.success(response.msg);
        getList();
        open.value = false;
      });
    }
  });
};
// 数据编辑区-->取消按钮
function cancel() {
  initForm();
  open.value = false;
}

/** ------------------数据操作区——按钮-------------------- */
// 清空或赋值表单数据
const initForm = () => {
  formRef.value?.resetFields();
};

// 数据操作区区--> 修改按钮
function handlePay(row: any) {
  initForm();
  const saleId = row.saleId;
  getSaleById(saleId).then(response => {
    saleInfo.value = response.data;
    form.value.saleId = response.data.saleId;
    form.value.amount = response.data.total;
    title.value = "支付订单[" + form.value.saleId + "]";
    open.value = true;
  });
}

// 数据操作区-->抽屉查看数据
const drawer = ref<boolean>(false);
const saleItems = ref<{
  no: string;
  roomRate: number;
  contact: string;
  phone: string;
  startDate: string;
  endDate: string;
  roomNumber: string;
  refund: string;
  deposit: number;
  list: [
    {
      specificDate: string;
      price: number;
    }
  ];
}>();
const saleTitle = ref("");
// 数据操作区--> 查看按钮
function handleView(row: any) {
  console.log(row);
  const paymentId = row.id;
  saleTitle.value = "订单[" + paymentId + "]详情";
  getOrderDetails(paymentId).then(response => {
    saleItems.value = response.data;
    console.log("下面list");
    console.log(saleItems.value.list);
    drawer.value = true;
  });
}
</script>

<style scoped>
.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  color: var(--el-color-primary);
  text-align: center;
  background: var(--el-color-primary-light-9);
  border-radius: 4px;
}
</style>
